#include "conversion_grayscale.h"

ConversionGrayscale::ConversionGrayscale(PNM* img) :
	Transformation(img)
{
}

ConversionGrayscale::ConversionGrayscale(PNM* img, ImageViewer* iv) :
	Transformation(img, iv)
{
}

PNM* ConversionGrayscale::transform()
{
	int width = image->width();
	int height = image->height();

	PNM* newImage = new PNM(width, height, QImage::Format_Indexed8);

	if (image->format() == QImage::Format_Mono)
	{
		for (int x=0; x<width; x++)
			for (int y=0; y<height; y++)
			{
				QColor pixel = image->pixel(x,y);
				int newColor;
				if(pixel.red() == 0 && pixel.green() == 0 && pixel.blue() == 0) newColor = PIXEL_VAL_MIN;
				else newColor = PIXEL_VAL_MAX;
				newImage->setPixel(x,y,newColor);
			}
	}
	else // if (image->format() == QImage::Format_RGB32)
	{
		for (int x=0; x<width; x++)
			for (int y=0; y<height; y++)
			{
				QRgb pixel = image->pixel(x,y);
				
				int gray = qRed(pixel)*0.3f + qGreen(pixel)*0.6f + qBlue(pixel)*0.1f;

				newImage->setPixel(x,y,gray);
			}
	}

	return newImage;
}
